package com.medisign.sign.log.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.data.redis.core.script.RedisScript;
import org.springframework.data.redis.support.atomic.RedisAtomicInteger;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.Set;
import java.util.concurrent.TimeUnit;

@Slf4j
@Component
public class RedisUtil {

    @Resource
    private RedisTemplate redisTemplate;

    /**
     * 普通存储
     * @param key
     * @param value
     * @return
     */
    public boolean set(String key, Object value) {
        try{
            redisTemplate.opsForValue().set(key, value);
            return true;
        }catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 普通存储设置过期时间
     * @param key
     * @param value
     * @param time
     * @return
     */
    public boolean set(String key, Object value, long time, TimeUnit timeUnit) {
        try {
            if (time > 0){
                redisTemplate.opsForValue().set(key, value, time, timeUnit);
            } else {
                set(key, value);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    public boolean tryLock(String redisKey, int time, TimeUnit timeUnit) {
        Boolean boo = redisTemplate.opsForValue().setIfAbsent(redisKey, redisKey, time, timeUnit);
        if (boo != null && boo){
            return true;
        }
        log.info("redisKey:[{}]", redisKey);
        return false;
    }

    public String getString(String key) {
        Object o = redisTemplate.opsForValue().get(key);
        if (null != o && StringUtils.isNotBlank(o.toString())) {
            return (String) o;
        }
        return null;
    }

    public boolean setRightList(String key, Object value) {
        try {
            redisTemplate.opsForList().rightPush(key, value);
            return true;
        } catch (Exception e) {
            log.error("{}", e);
            return false;
        }
    }

    public boolean setLeftList(String key, Object value) {
        try{
            redisTemplate.opsForList().leftPush(key, value);
            return true;
        }catch (Exception e) {
            log.error("{}", e);
        }
        return false;
    }

    public Object getLeftList(String key) {
        return redisTemplate.opsForList().rightPop(key);
    }

    public Object getAllList(String key) {
        return redisTemplate.opsForList().range(key, 0, -1);
    }

    public Long getListSize(String key) {
        return redisTemplate.opsForList().size(key);
    }


    public boolean addLockExpire(String redisKey, int time) {
        /*Object o = get(redisKey);
        if (null != o) {
            return true;
        }
        redisTemplate.setEnableTransactionSupport(true);
        redisTemplate.multi();
        redisTemplate.opsForValue().setIfAbsent(redisKey, redisKey);
        redisTemplate.expire(redisKey, time, TimeUnit.MINUTES);
        List result = redisTemplate.exec();// 这里result会返回事务内每一个操作的结果，如果setIfAbsent操作失败后，result[0]会为false。
        if(Boolean.parseBoolean(String.valueOf(result.get(0)))){
            return false;
        }
        return true;*/
        // 尝试获取锁
        Boolean boo = redisTemplate.opsForValue().setIfAbsent(redisKey, redisKey, time, TimeUnit.MINUTES);
        if (boo != null && boo) {
            //log.error(redisKey+"加锁成功!");
            return true;
        }
        log.error(redisKey+"加锁失败!");
        return false;
    }

    public Object get(String key) {
        Object o = redisTemplate.opsForValue().get(key);
        return o;
    }

    public Boolean expire(String key, long time, TimeUnit timeUnit) {
        Boolean expire = redisTemplate.expire(key, time, timeUnit);
        return expire;
    }

    /**
     * 获取过期时间
     * @param key
     * @return
     */
    public Long getExpire(String key, TimeUnit timeUnit) {
        Long expire = redisTemplate.opsForValue().getOperations().getExpire(key, timeUnit);
        return expire;
    }

    /**
     * 自增
     * @param key
     * @return
     */
    public Long incr(String key){
        /*RedisAtomicInteger entityIdCounter = new RedisAtomicInteger(key, redisTemplate.getConnectionFactory());
        int increment = entityIdCounter.getAndIncrement();
        return increment;*/
        return redisTemplate.opsForValue().increment(key);
    }


    /**
     * 获取
     * @param key
     * @return
     */
    public int getInt(String key){
        RedisAtomicInteger entityIdCounter = new RedisAtomicInteger(key, redisTemplate.getConnectionFactory());
        int increment = entityIdCounter.get();
        return increment;
    }

    public void delete(String key) {
        redisTemplate.delete(key);
    }

    public void deleteByKey(String key) {
        //log.error(key + "释放锁!");
        redisTemplate.delete(key);
    }


    private static final Long SUCCESS = 1L;

    /**
     * 获取锁
     * @param lockKey
     * @param value
     * @param expireTime：单位-秒
     * @return
     */
    public boolean getLock(String lockKey, String value, int expireTime){
        boolean ret = false;
        try{
            String script = "if redis.call('setNx',KEYS[1],ARGV[1]) == 1 then if redis.call('get',KEYS[1])==ARGV[1] then return redis.call('expire',KEYS[1],ARGV[2]) else return 0 end end";

            RedisScript<String> redisScript = new DefaultRedisScript<>(script, String.class);

            Object result = redisTemplate.execute(redisScript, Collections.singletonList(lockKey),value,expireTime);

            if(SUCCESS.equals(result)){
                return true;
            }

        }catch(Exception e){

        }
        return ret;
    }

    /**
     * 释放锁
     * @param lockKey
     * @param value
     * @return
     */
    public boolean releaseLock(String lockKey, String value){

        String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";

        RedisScript<String> redisScript = new DefaultRedisScript<>(script, String.class);

        Object result = redisTemplate.execute(redisScript, Collections.singletonList(lockKey),value);
        if(SUCCESS.equals(result)) {
            return true;
        }

        return false;
    }

    public boolean lock(String key, int value, long releaseTime){
        // 尝试获取锁
        Boolean boo = redisTemplate.opsForValue().setIfAbsent(key, value, releaseTime, TimeUnit.SECONDS);
        return boo != null && boo;
    }

    public void deleteByKeyPatten(String keyPatten) {
        Set<String> keys = redisTemplate.keys(keyPatten);
        if (!CollectionUtils.isEmpty(keys)) {
            redisTemplate.delete(keys);
        }
    }

    /**
     * 添加or更新hash的值
     *
     * @param key
     * @param field
     * @param value
     */
    public void hset(String key, String field, String value) {
        redisTemplate.opsForHash().put(key, field, value);
    }

    /**
     * 获取hash中field对应的值
     *
     * @param key
     * @param field
     * @return
     */
    public String hget(String key, String field) {
        Object val = redisTemplate.opsForHash().get(key, field);
        return val == null ? null : val.toString();
    }

    /**
     * 删除hash中field这一对kv
     *
     * @param key
     * @param field
     */
    public void hdel(String key, String field) {
        redisTemplate.opsForHash().delete(key, field);
    }
}
